

import { Radio, RadioChangeEvent, RadioGroupProps } from 'antd';
import './forms.scss';
import { useFormItemInit } from './hooks';
import { FormItemBaseProps } from './interface';
import React from 'react';
import { useDrag } from './drop.hooks';
import { Components } from '../..';




interface IProps extends FormItemBaseProps {
    optionType?: 'button' | 'default';
}
export default function MyRadio(props: IProps) {
    const { formControl, className = '', optionType='default', style={} } = props;
    const {
        value, setValue,
        readonly,
        outerClassName,
        options,
        layout,
        outerStyle,
        labelStyle,
    } = useFormItemInit(formControl, className, style);

    const [displayValue, setDisplayValue] = React.useState(value);
    React.useEffect(() => {
        const options = formControl.options;
        if (options?.length) {
            const option = options.find(v => v.value === value);
            if (option) {
                setDisplayValue(option.label);
            }
        }
    }, [value]);

    const onRadioChange = (e: RadioChangeEvent) => {
        const val = e.target.value;
        setValue(val);
        formControl.setValue(val);
    };

    const radioProps: RadioGroupProps = {
        value: value,
        className: 'radio',
        options,
        onChange: onRadioChange,
        disabled: readonly,
        optionType,
    };

    /** 拖拽排序 */
    const dropRef = React.useRef<HTMLDivElement>(null);
    useDrag({ dropRef, formControl });

    return (
        <div component-name='form-item' className={outerClassName} style={outerStyle} ref={dropRef}>
            <div className={`field ${layout}`}>
                <Components.forms.FormLabel formControl={formControl} style={labelStyle} />
                <div className='control'>
                    <div className="value">
                        {
                            readonly ?
                                <div className='readonly'>{displayValue}</div> :
                                <Radio.Group {...radioProps} />
                        }
                    </div>
                </div>
            </div>

        </div>
    )
}
